<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择原材料"
    width="50%"
    :destroy-on-close="true"
  >
    <el-transfer
      v-model="tempKeys"
      :data="materialOptions"
      :titles="['可选物料', '已选物料']"
      filterable
      filter-placeholder="请输入关键字搜索"
      :format="{ noChecked: '无选中项', hasChecked: '{checked} / {total} 已选' }"
      @change="handleTransferChange"
      style="height: 400px;"
    >
      <template #default="{ option }">
        {{ option.label }}
      </template>
    </el-transfer>

    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { Good } from '@/types/basic/BOM'
import request from '@/util/request'
// 接收父组件 v-model:modelValue 和 v-model:visible
const props = defineProps<{
  modelValue: Good[]
  visible: boolean
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: Good[]): void
  (e: 'update:visible', value: boolean): void
}>()

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
})

// 全部物料列表
const allMaterials = ref<Good[]>([])
onMounted(loadMaterials)
async function loadMaterials() {
  try {
    const resp = await request.post('basic/good/getAll')
    let list: any = resp.data
    if (!Array.isArray(list) && Array.isArray(resp.data.data)) {
      list = resp.data.data
    }
    allMaterials.value = Array.isArray(list) ? list : []
  } catch (err) {
    ElMessage.error('物料加载失败，请稍后重试')
    allMaterials.value = []
  }
}

// 转为 Transfer 可识别格式
const materialOptions = computed(() =>
  allMaterials.value.map(m => ({ key: m.id, label: `${m.code} - ${m.name}`, ...m }))
)

// 本地缓存选中 key
const tempKeys = ref<number[]>([])
watch(
  () => props.modelValue,
  value => {
    tempKeys.value = Array.isArray(value) ? value.map(m => m.id) : []
  },
  { immediate: true }
)

// Transfer change 回调
function handleTransferChange(newKeys: number[]) {
  console.log('[子组件] Transfer change keys:', newKeys)
}

function onCancel() {
  console.log('[子组件] 取消选择')
  emit('update:visible', false)
}

function onConfirm() {
  console.log('[子组件] onConfirm tempKeys:', tempKeys.value)
  const selected = allMaterials.value.filter(m => tempKeys.value.includes(m.id))
  console.log('[子组件] 过滤后的 selected:', selected)
  emit('update:modelValue', selected)
  emit('update:visible', false)
}
</script>

<style scoped>
/* 可根据需要自定义样式 */
</style>
